<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\System\Format;
use Illuminate\Http\Request;

class CacheService
{

    use Service;

    private $category = [ 'app', 'logs' ];

    /**
     * 文件管理首页
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function CacheIndexService( $request )
    {
        if ( ! $request->filled('static') ) request()->offsetSet('static', 'storage');
        if ( ! $request->filled('name') ) request()->offsetSet('name', 'framework');
        $name     = $request->input('name');
        $disk     = $this->getStorage($request->input('static'));
        $name_arr = explode('/', $name);
        if ( in_array(reset($name_arr), $this->category) ) return back()->with('error', $this->getErrorCode()::message(1015));
        $pic                      = $disk->allFiles($name);//$request->name目录的所有文件
        $res[ 'name' ][ 'count' ] = count($pic);
        $res[ 'pic' ]             = [];
        $res[ 'app' ]             = [];
        foreach ( $pic as $key => $value ) {
            $names   = explode('/', $value);
            $picName = array_slice($names, 0, count($names) - 1);//在数组中根据条件取出一段值
            foreach ( $picName as $k => $v ) $k == 0 ? $res[ 'pic' ][ $key ][ 'name' ] = $v . '/' : $res[ 'pic' ][ $key ][ 'name' ] .= $v . '/';//拼接文件名
            $res[ 'pic' ][ $key ][ 'title' ] = end($names);//文件名
            $res[ 'pic' ][ $key ][ 'last' ]  = $disk->time($value);//文件时间
            $res[ 'pic' ][ $key ][ 'size' ]  = $disk->size($value);//文件大小
        }
        return view('expansion.cache.index', compact('res', 'request'));
    }

    /**
     * 文件管理 树
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function CacheTreeService( $request )
    {
        $public = $this->getCommon()->TreeChildService('', $request->input('static', 'storage'), $request->input('name', ''), $request->input('true', ''), [
            'app', 'logs',
        ]);//树
        return data($public);
    }

    /**
     * 文件管理 删除
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function CacheDeleteService( $request )
    {
        $error = $this->getErrorCode();
        $disk  = $this->getStorage($request->input('static'));
        $title = $request->input('title');
        switch ( $request->input('status') ) {
            case 1:
                $str      = trimAll($title);//去除空格
                $name_arr = explode('/', $title);
                if ( in_array(reset($name_arr), $this->category) ) return back()->with('error', $error::message(1015));
                if ( ! $disk->exists($str) ) return back()->with('error', $error::message(1016));
                $disk->delete($str);//删除文件
                errorStorage('cache', '"删除文件名称" : ' . $title, '缓存文件删除成功', 'success', '删除缓存文件');
                return back()->with('success', $error::message(204));
                break;
            case 2:
                foreach ( $title as $value ) {//循环删除
                    $name_arr = explode('/', $value);
                    if ( in_array(reset($name_arr), $this->category) ) return message($error::message(1015));
                    $str = trimAll($title);//去除空格
                    if ( ! $disk->exists($str) ) return message($error::message(1016));
                    $disk->delete($str);//删除文件
                    errorStorage('cache', '"删除名称" : ' . $str, '缓存文件删除成功', 'success', '删除缓存文件');
                }
                return data();
                break;
            case 3:
                $name = $request->input('name');
                $file = $disk->allFiles($name);//获取$request->name下所有文件
                $true = explode('/', $name);
                if ( in_array(reset($true), $this->category) ) return message($error::message(1015));
                if ( reset($true) != 'framework' ) $disk->deleteDirectory($name);//清空除了framework的所有的目录及目录下的文件
                else foreach ( $file as $value ) $disk->delete($value);//否则就单个删除
                errorStorage('cache', '"删除文件夹名称" : ' . $name, '文件夹删除成功', 'success', '删除文件夹');
                return data();
            default:
                return back()->with('error', $error::message(1001));
                break;
        }
    }

    /**
     * 文件管理 创建
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function CacheStoreService( $request )
    {
        $error  = $this->getErrorCode();
        $static = $request->input('static');
        $status = $request->input('status');
        $title  = $request->input('title');
        $name   = $request->input('name');
        $disk   = $this->getStorage($static);
        switch ( $status ) {
            case 1:
                if ( ! $static || ! $title ) return back()->with('error', $error::message(1001));
                $true = explode('/', $title);
                if ( in_array(reset($true), $this->category) ) return back()->with('error', $error::message(1015));
                $disk->makeDirectory($title);//创建文件夹
                errorStorage('cache', '"文件夹名称" : ' . $title, '文件夹创建成功', 'success', '创建文件夹');
                return back()->with('success', $error::message(205));
                break;
            case 2:
                if ( ! $name || ! $static || ! $title ) return message($error::message(1001));
                $name = pathinfo($title);//获取文件信息
                $true = explode('/', $name);
                if ( in_array(reset($true), $this->category) ) return back()->with('error', $error::message(1015));
                if ( empty($name[ 'extension' ]) ) $name[ 'extension' ] = 'txt';//如果不存在后缀就给默认txt后缀
                $format      = Format::FindModel();//获取上传文件配置
                $ext         = strtolower($format->text);//转小写
                $extension   = strtolower($name[ 'extension' ]);
                $allow_types = explode(',', $ext);
                if ( ! in_array($extension, $allow_types) ) return back()->with('error', $error::message(1004));
                $fileName = $name[ 'filename' ] . '.' . $name[ 'extension' ];//拼接文件名
                $name     = $disk->exists($name . '/' . $fileName);//获取文件
                if ( $name ) return back()->with('error', $error::message(1017));
                $disk->put($name . '/' . $fileName, '');//创建文件
                errorStorage('cache', '"文件名" : ' . $fileName . ' "路径" : ' . $name . ' "用户手动输入" : ' . $title, $name . '/' . $fileName . '文件创建成功', 'success', '创建文件');
                return back()->with('success', $error::message(206));
                break;
            default:
                return back()->with('error', $error::message(1001));
        }
    }

    /**
     * 文件管理 查看文件
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function CacheEditService( $request )
    {
        $error  = $this->getErrorCode();
        $static = $request->input('static');
        $name   = $request->input('name');
        $title  = $request->input('title');
        if ( ! $static || ! $name || ! $title ) return back()->with('error', $error::message(1001));
        $true = explode('/', $name);
        if ( in_array(reset($true), $this->category) ) return back()->with('error', $error::message(1015));
        $disk = $this->getStorage($static);
        $url  = trimAll($title);//去除空格
        if ( ! $disk->exists($url) ) return back()->with('error', $error::message(1016));
        $names = explode('/', $url);
        $str   = end($names);//获取数组最后一个值
        $res   = $disk->get($title);//获取文件url
        return view('expansion.cache.edit', compact('res', 'str', 'url', 'request'));
    }

    /**
     * 文件管理 修改文件
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function CacheUpdateService( $request )
    {
        $error = $this->getErrorCode();
        if ( ! $request->filled('category') || ! $request->filled('name') || ! $request->filled('url') ) return back()->with('error', $error::message(1001));
        $url      = $request->input('url');
        $category = rtrim($request->input('category'), "/");
        $true     = explode('/', $category);
        if ( in_array(reset($true), $this->category) ) return back()->with('error', $error::message(1015));
        $disk = $this->getStorage($request->input('static', 'storage'));
        $name = pathinfo($request->input('name'));//获取文件信息
        ! empty($name[ 'extension' ]) ? $name[ 'extension' ] : $name[ 'extension' ] = '';
        $format      = Format::FindModel([ 'text', 'text_cate', 'text_size' ]);//获取上传配置
        $ext         = strtolower($format->text);//转小写
        $extension   = strtolower($name[ 'extension' ]);
        $allow_types = explode(',', $ext);
        if ( $name[ 'extension' ] ) if ( ! in_array($extension, $allow_types) ) return back()->with('error', $error::message(1004));
        $size     = size($format->text_cate, $format->text_size);//用类型和大小获取值
        $sizeName = $disk->size($url);//获取文件大小值
        if ( $sizeName > $size ) return back()->with('error', '文本不能大于' . maxsize($size));
        if ( $name[ 'extension' ] ) $fileName = $name[ 'filename' ] . '.' . $name[ 'extension' ];
        else $fileName = $name[ 'filename' ];
        unset($name);
        $urls = trimAll($url);//去除空格
        if ( ! $disk->exists($urls) ) return back()->with('error', $error::message(1016));
        unset($name);
        $name     = '';
        $fileInfo = $category . '/' . $fileName;
        if ( $fileInfo != $urls ) $name = $disk->exists($fileInfo);
        if ( $name ) return back()->with('error', $error::message(1017));
        if ( $fileInfo != $urls ) $disk->move($url, $fileInfo);//移动文件
        $disk->put($fileInfo, $request->input('text'));//写入文件
        $data = '"原路径" : ' . $url . ' "现文件名" : ' . $fileName . ' "修改内容" : ' . $request->input('text') . ' "现路径" : ' . $fileInfo;
        errorStorage('cache', $data, '修改缓存文件成功', 'success', '修改缓存文件');
        return redirect(route('expansion.cache.index'))->with('success', '修改缓存文件成功');
    }
}
